package com.zhou.kotlin_car_data_list.ui

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import com.zhou.kotlin_car_data_list.R
import com.zhou.kotlin_car_data_list.adapter.BrandListAdapter
import com.zhou.kotlin_car_data_list.bean.Brand
import com.zhou.kotlin_car_data_list.bean.BrandListBean
import com.zhou.kotlin_car_data_list.bean.ResultBean
import com.zhou.kotlin_car_data_list.databinding.ActivityBrandListBinding
import com.zhou.kotlin_car_data_list.utils.CarApi
import com.zhou.kotlin_car_data_list.utils.RetrofitUtils
import retrofit2.Call
import retrofit2.Response

class BrandListActivity : AppCompatActivity() {

    val binding: ActivityBrandListBinding by lazy {
        DataBindingUtil.setContentView(this, R.layout.activity_brand_list)
    }

    val mData: MutableList<ResultBean> = mutableListOf()
    val adapter: BrandListAdapter by lazy {
        BrandListAdapter(this, mData)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val bean = intent.getParcelableExtra("logoBean") as? Brand
        binding.title = bean?.brandName
        binding.brandlistAdapter = adapter
        bean?.id?.let { loadDatas(it) }
    }

    private fun loadDatas(id: String) {
        val api = RetrofitUtils.getApi(CarApi.baseUrl, CarApi::class.java)
        val call = api.getBrandList(CarApi.key, id)
        call?.enqueue(object : retrofit2.Callback<BrandListBean> {
            override fun onResponse(call: Call<BrandListBean>, response: Response<BrandListBean>) {
                response.body()?.result?.let {
                    mData.addAll(it)
                    adapter.notifyDataSetChanged()
                }
            }

            override fun onFailure(call: Call<BrandListBean>, t: Throwable) {
                TODO("Not yet implemented")
            }

        })
    }
}